<?php
/**
 * Created by PhpStorm.
 * User: xuzhong
 * Date: 2025/4/2
 * Time: 13:49
 */


namespace app\admin\service;

use app\admin\common\ServiceResponse;
use app\admin\model\Discount as DiscountModel;
use app\admin\model\Images;
use app\facade\Mail;
use think\facade\Db;

class Discount extends BaseService
{
    use ServiceResponse;

    protected $model;

    public function __construct()
    {
        $this->model = new DiscountModel();
        parent::__construct();
    }

    /**
     * @describe 获取折扣列表
     * @author: 徐众
     * @date: 2025-04-02 13:02:26
     * @param [] type
     * @return Renderable
     */
    public function getList($keywords,$status, $page, $limit): array
    {
        if (0 >= $page || 100 < $limit) {
            return $this->error(100002);
        }
        $where= ['is_del'=>0];
        if ($status !== null && $status !== ''){
            $where= ['status'=>$status];
        }
        $sql = $this->model->where($where);
        if($keywords){
            $sql = $sql->whereRaw(
                "code_title like ? " ,['%'.$keywords."%" ]
            );
        }

        $total = $sql->count();
        if (!$total) {
            return $this->success(['list' => [], 'total' => 0]);
        }
        $list = $sql->page($page, $limit)->order('id DESC')->append(['discount_category_value'])->select()->toArray();
        $creator_id = array_column($list,'creator');
        $updater_id = array_column($list,'updater');
        $ids = array_unique(array_merge($creator_id,$updater_id));
        $op = Db::name('operator')->whereIn('id',$ids)->select()->toArray();
        $op = array_column($op,null,'id');
        foreach ($list as &$value){
            $str = $value['discount_type'] == 1?$value['discount_value'].'%':'$'.$value['discount_value'];
            $type = $value['discount_category'] == 1?" off products" : " off entire order";
            $value['code_title_value'] = $str.$type;
            if($value['creator']){
                $value['creator'] = $op[$value['creator']]['cname']??'';
            }
            if($value['updater']){
                $value['updater'] = $op[$value['updater']]['cname']??'';
            }
        }
        return $this->success(['list' => $list, 'total' => $total]);
    }
    /**
     * 创建折扣
     * @param array $data 创建物流公司的数据
     */
    public function create($data)
    {
        $is_send = false;
        if(!empty($data)){
            if(isset($data['discount_category']) && $data['discount_category'] ==2){
                $data['applies_to_type']=null;
                $data['applies_to_value'] =null ;
            }
            if(isset($data['min_purchase_req_type']) && $data['min_purchase_req_type'] ==1){
                $data['min_purchase_req_value']=null;
            }
            if(isset($data['isSend']) && $data['isSend'] ==true){
                $is_send = true;
            }
            if(isset($data['eligibility_type']) && $data['eligibility_type'] == 1){
                $data['eligibility_value']=null;
            }
            if(isset($data['max_discount_uses_type']) && $data['max_discount_uses_type'] ==2){
                $data['max_discount_uses_value'] = null;
            }
            $data['discount_parent_category'] = $this->model::PARENT_CATEGOTY[$data['discount_category']]??0;
            $data['method'] = 1;
            $data['status'] = 1;
            $data['source'] = 1;
            $data['create_time'] = date('Y-m-d H:i:s');
            try {
                $res = $this->model->create($data);
                if ($res) {
                    if($is_send){
                        Mail::send('coupon',$data);
                    }
                    $this->logger->logOperation($res->id,'Discount','创建','创建优惠券');
                    return $this->success();
                } else {
                    return $this->error(500001);
                }
            } catch (\Throwable $th) {
                return $this->error(500001, '服务器内部错误：' . $th->getMessage());
            }
        }else{
            return $this->error(500001, '服务器内部错误' );
        }

    }

    /**
     *  修改折扣状态
     */
    public function status($param)
    {

        $result = $this->model->where('id', 'in', $param['id'])->find();

        if (!$result) {
            return $this->error(500001, '未找到数据');
        }

        $result->status = $param['status'];
        $result->update_time = date('Y-m-d H:i:s',time());

        if ( $result->save() ) {
            return $this->success();
        } else {
            return $this->error(500001);
        }
    }
    /**
     * 获取文章详情
     * @param int $id 物流公司ID
     */
    public function getOneById($id)
    {
        $customerContact = $this->model
            ->field('id,discount_category,code_title,discount_type,discount_value,applies_to_type,applies_to_value,min_purchase_req_type,min_purchase_req_value,eligibility_type,eligibility_value,max_discount_uses_type,max_discount_uses_value,activedate_start,activedate_end')
            ->find($id);
        $data = $customerContact->toArray();
        $plist = [];
        $clist = [];
        if($data['applies_to_value']){
            if($data['applies_to_type'] == 1){
                $plist = Db::name('product_merge')->whereIn('id',$data['applies_to_value'])->field('id,productname as name')->select()->toArray();
            }
            if($data['applies_to_type'] == 2){
                $plist = Db::name('product')->whereIn('id',$data['applies_to_value'])->field('id,cname as name')->select()->toArray();
            }
        }
        if($data['eligibility_value']){
            $clist = Db::name('customer')->whereIn('id',$data['eligibility_value'])->field('id,cusname as name')->select()->toArray();
        }
        $data['plist'] = $plist;
        $data['clist'] = $clist;
        return $this->success($data);
    }

    /**
     * 获取折扣绩效
     * @param int $id 物流公司ID
     */
    public function getDiscountTotal($id){
        $data['total'] = 0;
        $data['sum'] = 0.0;
        $discount = Db::name('order_relation')->where('discount_id',$id)->where('is_del',0)->select()->toArray();
        if(count($discount) == 0 ){
            return $this->success($data);
        }
        $order_ids = array_column($discount,'order_id');
        $order = Db::name('order')->where(
            [
               ['pay_status','in',[3,4]],
               ['status','<>',70],
               ['is_del','=',0],
               ['id','in',$order_ids],
            ]
        )->sum('pay_amount');
        $data['total'] = count($discount);
        $data['sum'] = $order;
        return $this->success($data);
    }


    /**
     * 更新销售人员
     * @param int $id 物流公司ID
     * @param array $data 更新物流公司的数据
     */
    public function update($data)
    {
        if(isset($data['discount_category']) && $data['discount_category'] ==2){
            $data['applies_to_type']=null;
            $data['applies_to_value'] =null ;
        }
        if(isset($data['min_purchase_req_type']) && $data['min_purchase_req_type'] ==1){
            $data['min_purchase_req_value']=null;
        }
        if(isset($data['eligibility_type']) && $data['eligibility_type'] == 1){
            $data['eligibility_value']=null;
        }
        if(isset($data['max_discount_uses_type']) && $data['max_discount_uses_type'] ==2){
            $data['max_discount_uses_value'] = null;
        }
        $res = $this->model->where('id', $data['id'])->find();
        if (!$res) {
            return false;
        }
        foreach ($data as $key => $value) {
            if ($res->$key != $value) {
                $res->$key = $value;
            }
        }
        $result = $res->save();
        if ($result) {
            $this->logger->logOperation($res->id,'Article','更新','更新文章');
            return $this->success();
        } else {
            return $this->error(500001);
        }
    }

    /**
     * @describe 删除销售人员
     * @author: 徐众
     * @date: 2025-04-02 13:02:26
     * @param [] type
     * @return Renderable
     */
    public function delete($param): array
    {
        #校验参数
        if (!isset($param['ids']) || empty($param['ids'])) {
            return $this->error(100001, '操作失败');
        }
        #查询数据是否存在
        $result = $this->model->where('id', 'in', $param['ids'])->where('is_del', '=', 0)->select()->toArray();

        if (!empty($result)) {
            #更新记录
            $update = $this->model->where('id', 'in', $param['ids'])->where('is_del', '=', 0)->update([
                'is_del' => time()
            ]);
            if ($update) {
                #尝试记录操作日志 不影响主流程
                try {
                    $this->logger->logOperation($param['ids'], 'Article', '删除', '删除文章');
                } catch (\Exception $e) {
                    #记录日志或其他操作
                }
                return $this->success();
            } else {
                return $this->error(500001, '操作失败');
            }

        } else {
            #未找到记录返回失败
            return $this->error(400000, '未找到相关数据');
        }

    }

    /**
     * @describe
     * @author: Bobo
     * @date: 2025-02-13 11:03:36
     * @param [type] @required
     * @return Renderable
     */
    public function getFieldEnum($field = 'all')
    {
        $res = $this->model->getFieldEnum($field);
        return [
            'code' => 0,
            'data' => $res
        ];
    }
}